import router from '@/router'

const Ajax = {};
Ajax.install = function (Vue, options) {
  // 4. 添加实例方法
  Vue.prototype.$ajax = function (uri, method, data, callback) {
    // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
    // https://developer.mozilla.org/en-US/docs/Web/API/FormData
    // http://blog.csdn.net/ldc726/article/details/52210016
    // FormData will always be sent as multipart/form-data，所以上传文件的时候才用
    // URLSearchParams 是 x-www-form-urlencoded
    const formData = new URLSearchParams();
    if (data) {
      Object.keys(data).forEach(function (key) {
        console.log(key + ' = ' + data[key]);
        formData.append(key, data[key]);
      });
    }
    const url = new URL(window.location.protocol + '//' + window.location.host.replace("8081", "8080") + '/' + uri);
    const options = {
      method: method,
      headers: {},
      body: null
    };
    if (method === 'GET') {
      url.search = formData;
    }
    else {
      options.body = formData;
    }
    // https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
    fetch(url, options).then(res => {
      console.log(res);
    if (!res.ok) {
      Vue.prototype.$Message.error('请求超时，请稍后再试');
      return;
    }
    res.json().then(function (data) {
      if (!data.status) {
        Vue.prototype.$Message.error('返回数据错误');
        return;
      }
      if (data.status !== 200)
        Vue.prototype.$Message.error(data.message);
      else {
        callback(data);
      }
    });
  }).catch(error => {
      console.log(error);
  });
  };
};
export default Ajax;
